package com.example.zhunongzonghe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhunongzonghe.beans.ZnFarmhouseReserveBean;
import com.example.zhunongzonghe.common.Result;
import com.example.zhunongzonghe.entity.ZnFarmhouse;
import com.example.zhunongzonghe.entity.ZnFarmhouseReserve;
import com.example.zhunongzonghe.service.IZnFarmhouseReserveService;
import com.example.zhunongzonghe.service.IZnFarmhouseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


@RestController
@RequestMapping("/znFarmhouseReserve")
public class ZnFarmhouseReserveController  {
    @Autowired
    private IZnFarmhouseReserveService znFarmhouseReserveService;
    @Autowired
    private IZnFarmhouseService iZnFarmhouseService;

    @GetMapping("/getReserveAll")
    public Result getReserveAll(@RequestParam("createPage")Integer createPage,
                                @RequestParam("pageSize")Integer pageSize,
                                @RequestParam("input")String selectInfo
                                ){
        if (createPage==null || pageSize==null) return new Result(false, "数据异常", 400);
        Page<ZnFarmhouseReserveBean> beanPage =
                znFarmhouseReserveService.getReserveAll(createPage,pageSize,selectInfo);
        return new Result(true, "成功", 200,beanPage);
    }
    /**
     * 进行预定
     * @param znFarmhouseReserve
     * @return
     */
    @PostMapping("/subReserveInfo")
    public Result subReserveInfo(@RequestBody ZnFarmhouseReserve znFarmhouseReserve, Principal principal){
        System.out.println("接收到的数据为----："+znFarmhouseReserve);
        if (znFarmhouseReserve==null) return new Result(false,"数据出错，请联系管理员",400);
        LambdaQueryWrapper<ZnFarmhouseReserve> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZnFarmhouseReserve::getHouseId,znFarmhouseReserve.getHouseId())
                .eq(ZnFarmhouseReserve::getUsername,principal.getName());
        List<ZnFarmhouseReserve> reserveList = znFarmhouseReserveService.list(wrapper);
        if (reserveList.isEmpty()) {
            String reserveNumber = generateOrderNumber();
            znFarmhouseReserve.setOrderTime(LocalDateTime.now());
            znFarmhouseReserve.setReserveNumber(reserveNumber);
            znFarmhouseReserve.setEvaluateStatus(0);
            znFarmhouseReserve.setReserveStatus(0);
            znFarmhouseReserve.setCreateTime(LocalDateTime.now());
            znFarmhouseReserveService.save(znFarmhouseReserve);
            return new Result(true, "预定成功", 200);
        } else if (reserveList.size() > 0 ) {
            ZnFarmhouseReserve reserve = reserveList.get(0);
            if (reserve.getPayStatus() == 0) {
                return new Result(false, "预定失败,该订单尚未完成交易", 400);
            } else {
                String reserveNumber = generateOrderNumber();
                znFarmhouseReserve.setOrderTime(LocalDateTime.now());
                znFarmhouseReserve.setReserveNumber(reserveNumber);
                znFarmhouseReserveService.save(znFarmhouseReserve);
                return new Result(true, "预定成功", 200);
            }
        } else {
            return new Result(false, "预定失败", 400);
        }
    }

    /**
     * 查询当前登录用户订单
     * @param userName
     * @return
     */
    @GetMapping("/queryMyReserve")
    public Result<List<ZnFarmhouseReserveBean>> MyReserve(@RequestParam("userName") String userName){
        if (userName==null) return new Result<>(false,"数据错误，请联系管理员",400);
        LambdaQueryWrapper<ZnFarmhouseReserve> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZnFarmhouseReserve::getUsername,userName);
        List<ZnFarmhouseReserve> reserveList = znFarmhouseReserveService.list(wrapper);
        List<ZnFarmhouseReserveBean> beanList = new ArrayList<>();
        reserveList.forEach(znFarmhouseReserve -> {
            ZnFarmhouseReserveBean bean = new ZnFarmhouseReserveBean();
            BeanUtils.copyProperties(znFarmhouseReserve,bean);
            beanList.add(bean);
            beanList.forEach(znFarmhouseReserveBean -> {
                ZnFarmhouse znFarmhouse = iZnFarmhouseService.SearcHouseInfo(znFarmhouseReserve.getHouseId());
                bean.setHouseName(znFarmhouse.getHouseName());
            });
        });
        System.out.println("用户名为：======"+beanList);
        return new Result<>(true,"查询成功",200,beanList);
    }

    @DeleteMapping("deleteMyReserve/{reserve}")
    public Result deleteMyReserve(@PathVariable Integer reserve){
        if (reserve==null) return null;
        znFarmhouseReserveService.removeById(reserve);
        return new Result(true,"删除成功",200);
    }

    /**
     * 后台删除预定信息
     * @param reserveId
     * @return
     */
    @DeleteMapping("delReservat/{reserveId}")
    public Result delReservat(@PathVariable Integer reserveId){
        if (reserveId==null) return null;
        znFarmhouseReserveService.removeById(reserveId);
        return new Result(true,"删除成功",200);
    }

    /**
     * 后台接受预定
     * @param reserveId
     * @return
     */
    @RequestMapping("/takeInReserva")
    public Result takeInReserva(Integer reserveId){
        if (reserveId==null) new Result(false,"数据异常",400);
        ZnFarmhouseReserve reserve = znFarmhouseReserveService.getById(reserveId);
        reserve.setReserveStatus(1);
        znFarmhouseReserveService.updateById(reserve);
        return new Result(true,"成功",200);
    }
    /**
     * 后台取消预定
     * @param reserveId
     * @return
     */
    @RequestMapping("/cancelReserva")
    public Result cancelReserva(Integer reserveId){
        if (reserveId==null) new Result(false,"数据异常",400);
        ZnFarmhouseReserve reserve = znFarmhouseReserveService.getById(reserveId);
        reserve.setReserveStatus(4);
        znFarmhouseReserveService.updateById(reserve);
        return new Result(true,"成功",200);
    }
    /**
     * 后台处理用户申请的取消预定
     * @param reserveId
     * @return
     */
    @RequestMapping("/UserCancelReserve")
    public Result UserCancelReserve(Integer reserveId){
        if (reserveId==null) new Result(false,"数据异常",400);
        ZnFarmhouseReserve reserve = znFarmhouseReserveService.getById(reserveId);
        reserve.setReserveStatus(3);
        znFarmhouseReserveService.updateById(reserve);
        return new Result(true,"成功",200);
    }
    /**
     * 后台处理用户申请的取消预定
     * @param reserveId
     * @return
     */
    @RequestMapping("/AdminCancelReserve")
    public Result AdminCancelReserve(Integer reserveId){
        if (reserveId==null) new Result(false,"数据异常",400);
        ZnFarmhouseReserve reserve = znFarmhouseReserveService.getById(reserveId);
        reserve.setReserveStatus(4);
        znFarmhouseReserveService.updateById(reserve);
        return new Result(true,"成功",200);
    }
    /**
     * 当前用户申请取消预定
     * @param reserveId
     * @return
     */
    @RequestMapping("/UserApplyForCancelReserve")
    public Result UserApplyForCancelReserve(Integer reserveId){
        if (reserveId==null) new Result(false,"数据异常",400);
        ZnFarmhouseReserve reserve = znFarmhouseReserveService.getById(reserveId);
        reserve.setReserveStatus(2);
        znFarmhouseReserveService.updateById(reserve);
        return new Result(true,"成功",200);
    }
    /**
     * 预定订单交易完成
     * @param reserveId
     * @return
     */
    @RequestMapping("/CloseTheDeal")
    public Result CloseTheDeal(Integer reserveId){
        if (reserveId==null) new Result(false,"数据异常",400);
        ZnFarmhouseReserve reserve = znFarmhouseReserveService.getById(reserveId);
        reserve.setReserveStatus(5);
        znFarmhouseReserveService.updateById(reserve);
        return new Result(true,"成功",200);
    }
    public static String generateOrderNumber() {
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();

        // 格式化日期部分，例如：yyyyMMddHHmmss
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String datePart = dateFormat.format(new Date(timestamp));

        // 生成随机数部分，例如：0000 到 9999
        Random random = new Random();
        int randomPart = random.nextInt(10000);

        // 组合订单号
        String orderNumber = datePart + String.format("%04d", randomPart);

        return orderNumber;
    }


}